﻿namespace RuoVea.OmiApi.Reports.Util;

/// <summary>
/// 代码生成数据库连接
/// </summary>
public static class DbProvider
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="connStr"></param>
    /// <param name="dbType"></param>
    /// <param name="isAutoCloseConnection"></param>
    /// <returns></returns>
    public static SqlSugar.SqlSugarClient GetSugarDbContextBySelected(string connStr, int dbType = (int)SqlSugar.DbType.SqlServer, bool isAutoCloseConnection = true)
    {
        var db = new SqlSugar.SqlSugarClient(new List<SqlSugar.ConnectionConfig>()
            {
                new SqlSugar.ConnectionConfig(){
                    ConnectionString = connStr,
                    DbType = (SqlSugar.DbType)dbType,
                    IsAutoCloseConnection = isAutoCloseConnection,//开启自动释放模式和EF原理一样
                    InitKeyType = SqlSugar.InitKeyType.Attribute,//从特性读取主键和自增列信息
                },
            });

        //CodeDb = db;
        db.Ado.IsEnableLogEvent = true;
        //调试信息
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            var param = db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value));
            Console.WriteLine ($"【sql语句】{sql}，{param}\n");
        };
        db.Aop.OnError = (e) =>
        {
            Console.WriteLine($"执行SQL出错：{e.Message}", e);
        };
        //SQL执行完
        db.Aop.OnLogExecuted = (sql, pars) =>
        {
            //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate) 
        };
        return db;
    }
     
    /// <summary>
    /// 根据DBType返回C#数据类型
    /// </summary>
    /// <param name="t">
    /// </param>
    /// <returns></returns>
    public static string GetCSharpSimpleType(Type t)
    {
        string stype = t.ToString();

        string sTempDatatype = stype switch
        {
            "System.Int16" or "System.Int32" or "System.UInt16" or "System.UInt32" => "int",
            "System.Int64" or "System.UInt64" => "long",
            "System.Object" => "object",
            "System.Byte" or "System.Byte[]" => "byte",
            "System.Guid" => "Guid",
            "System.Decimal" => "decimal",
            "System.Double" => "double",
            "System.Boolean" => "bool",
            "System.DateTime" => "DateTime",
            _ => "string",
        };
        return sTempDatatype;
    }
}
